package com.swz.dcrm.ui.car;


import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.flexbox.JustifyContent;
import com.swz.dcrm.adpter.CarModelTagAdapter;
import com.swz.dcrm.adpter.GlobalAdapter;
import com.swz.dcrm.model.BaseResponse;
import com.swz.dcrm.model.Car;
import com.swz.dcrm.model.CarModel;
import com.swz.dcrm.model.CarModelRelativeMerits;
import com.swz.dcrm.model.CarModelTag;
import com.swz.dcrm.model.Input;
import com.swz.dcrm.ui.base.BaseFragment;
import com.swz.dcrm.R;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.navigation.fragment.NavHostFragment;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import butterknife.BindView;
import butterknife.OnClick;

import com.swz.dcrm.R;
import com.swz.dcrm.ui.viewmodel.CarManagementViewModel;
import com.swz.dcrm.ui.viewmodel.MainViewModel;
import com.swz.dcrm.util.CustomDecoration;
import com.swz.dcrm.util.Tool;
import com.xh.baselibrary.callback.OnClickListener;
import com.zhouwei.mzbanner.MZBannerView;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

/**
 * A simple {@link Fragment} subclass.
 */
public class CarCompareFragment extends BaseFragment {

    @BindView(R.id.mz_view)
    MZBannerView<CarModel> mzBannerView;
    @BindView(R.id.tv_car_model)
    TextView tvCarModel;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.et_tag)
    EditText etTag;
    @BindView(R.id.ll_indicator)
    LinearLayout llIndicator;
    @BindView(R.id.rv1)
    RecyclerView rv1;
    @BindView(R.id.rv2)
    RecyclerView rv2;
    @BindView(R.id.rv3)
    RecyclerView rv3;
    @BindView(R.id.rv4)
    RecyclerView rv4;
    @BindView(R.id.ll_input)
    LinearLayout llInput;

    CarModelTagAdapter carModelTagAdapter1;
    CarModelTagAdapter carModelTagAdapter2;
    CarModelTagAdapter carModelTagAdapter3;
    CarModelTagAdapter carModelTagAdapter4;
    private CarModelTag mCarModelTag;
    private List<View> indicators = new ArrayList<>();
    @Inject
    CarManagementViewModel carManagementViewModel;
    @Inject
    MainViewModel mainViewModel;

    public static CarCompareFragment newInstance() {

        return new CarCompareFragment();
        // Required empty public constructor
    }

    @Override
    public void onLoadRetry() {
        if (!isNetworkConnected(getContext())) {
            mHolder.showLoadingStatus(GlobalAdapter.NET_ERROR);
            return;
        }
        carManagementViewModel.getCompareCars().observe(this, new Observer<BaseResponse<List<CarModel>>>() {
            @Override
            public void onChanged(BaseResponse<List<CarModel>> listBaseResponse) {
                if(listBaseResponse==null){
                    return;
                }
                if (listBaseResponse.isSuccess()) {
                    mzBannerView.setPages(listBaseResponse.getData(), () -> new CarModelHolder());
                    indicators = new ArrayList<>();
                    llIndicator.removeAllViews();
                    for (int i = 0; i < listBaseResponse.getData().size(); i++) {
                        TextView tv = new TextView(getContext());
                        if (i == 0) {
                            tv.setBackground(getResources().getDrawable(R.drawable.shape_circle_blue));
                        } else {
                            tv.setBackground(getResources().getDrawable(R.drawable.shape_circle_gray));
                        }
                        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(Tool.dip2px(getContext(), 6), Tool.dip2px(getContext(), 6), 0);
                        layoutParams.setMargins(2, 0, 2, 0);//设置左上右下四个margin值;
                        //layoutParams是让linearLayout知道如何摆放自己孩子的位置的;
                        llIndicator.addView(tv, layoutParams);
                        indicators.add(tv);
                    }
                    mzBannerView.getViewPager().addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                        @Override
                        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                        }

                        @Override
                        public void onPageSelected(int position) {
                            getCarModelRelativeMerits(listBaseResponse.getData().get(position));
                            for (View view : indicators) {
                                view.setBackground(getResources().getDrawable(R.drawable.shape_circle_gray));
                            }

                            indicators.get(position).setBackground(getResources().getDrawable(R.drawable.shape_circle_blue));
                        }

                        @Override
                        public void onPageScrollStateChanged(int state) {

                        }
                    });
                    if(listBaseResponse.getData().size()>0){
                        getCarModelRelativeMerits(listBaseResponse.getData().get(0));
                    }
                }
                carManagementViewModel.getCompareCarsResult().removeObserver(this);
            }
        });

    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        onLoadRetry();
    }

    @Override
    public int layoutId() {
        return R.layout.fragment_car_compare;
    }

    @Override
    public boolean initView() {
        getDigger().inject(this);
        etTag.setFocusable(true);
        etTag.setFocusableInTouchMode(true);

        carManagementViewModel.getEdit().observe(this, aBoolean -> {

            if (aBoolean != null && aBoolean) {

                carModelTagAdapter1.edit(true);
                carModelTagAdapter2.edit(true);
                carModelTagAdapter3.edit(true);
                carModelTagAdapter4.edit(true);
            } else if (aBoolean != null) {
                carModelTagAdapter1.edit(false);
                carModelTagAdapter2.edit(false);
                carModelTagAdapter3.edit(false);
                carModelTagAdapter4.edit(false);
            }
        });
        mzBannerView.setIndicatorVisible(false);

        FlexboxLayoutManager manager = new FlexboxLayoutManager(getContext()){
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        manager.setFlexDirection(FlexDirection.ROW);
        manager.setFlexWrap(FlexWrap.WRAP);
        manager.setJustifyContent(JustifyContent.FLEX_END);
        rv1.setLayoutManager(manager);
        rv1.addItemDecoration(new CustomDecoration(getContext(), 10, 0, 0, 10));
        FlexboxLayoutManager manager1 = new FlexboxLayoutManager(getContext()){
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        manager1.setFlexDirection(FlexDirection.ROW);
        manager1.setFlexWrap(FlexWrap.WRAP);
        manager1.setJustifyContent(JustifyContent.FLEX_END);
        rv3.setLayoutManager(manager1);
        rv3.addItemDecoration(new CustomDecoration(getContext(), 10, 0, 0, 10));

        FlexboxLayoutManager manager2 = new FlexboxLayoutManager(getContext()){
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        manager2.setFlexDirection(FlexDirection.ROW);
        manager2.setFlexWrap(FlexWrap.WRAP);
        manager2.setJustifyContent(JustifyContent.FLEX_START);
        rv2.setLayoutManager(manager2);
        rv2.addItemDecoration(new CustomDecoration(getContext(), 10, 0, 0, 10));
        FlexboxLayoutManager manager3 = new FlexboxLayoutManager(getContext()){
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        manager3.setFlexDirection(FlexDirection.ROW);
        manager3.setFlexWrap(FlexWrap.WRAP);
        manager3.setJustifyContent(JustifyContent.FLEX_START);
        rv4.setLayoutManager(manager3);
        rv4.addItemDecoration(new CustomDecoration(getContext(), 10, 0, 0, 10));
        carManagementViewModel.getCurrentNeedCompareCar().observe(this, carModel -> {
            tvCarModel.setText(carModel.getName());
            tvPrice.setText(carModel.getCarPrice() + "万");
            carManagementViewModel.getCarModelRelativeMerits(carModel.getId())
                    .observe(this, new Observer<BaseResponse<CarModelRelativeMerits>>() {
                        @Override
                        public void onChanged(BaseResponse<CarModelRelativeMerits> carModelRelativeMeritsBaseResponse) {

                            if (carModelRelativeMeritsBaseResponse == null) {
                                return;
                            }
                            carManagementViewModel.getCarModelRelativeMerits().removeObserver(this);
                            if (carModelRelativeMeritsBaseResponse.isSuccess()) {
                                List<CarModelTag> list = new ArrayList<>();
                                list.addAll(carModelRelativeMeritsBaseResponse.getData().getGoodPointTagList());
                                CarModelTag carModelTag = new CarModelTag();
                                carModelTag.setTagContext("添加标签");
                                carModelTag.setCarModelId(carModel.getId());
                                list.add(carModelTag);
                                carModelTagAdapter1 = new CarModelTagAdapter(getContext(),
                                        list, 1, 1);

                                List<CarModelTag> list1 = new ArrayList<>();
                                list1.addAll(carModelRelativeMeritsBaseResponse.getData().getBadPointTagList());
                                list1.add(carModelTag);
                                carModelTagAdapter3 = new CarModelTagAdapter(getContext(),
                                        list1, 3, 3);
                                carModelTagAdapter1.setOnClickListener(carModelTagOnClickListener1);
                                carModelTagAdapter3.setOnClickListener(carModelTagOnClickListener3);
                                carModelTagAdapter1.setOnAddItemListener(onAddItemListener);
                                carModelTagAdapter3.setOnAddItemListener(onAddItemListener);
                                rv1.setAdapter(carModelTagAdapter1);
                                rv3.setAdapter(carModelTagAdapter3);
                            }
                        }
                    });
        });

        getActivity().getWindow().getDecorView().addOnLayoutChangeListener(onLayoutChangeListener);
        return true;
    }

    OnClickListener<CarModelTag> carModelTagOnClickListener1 = new OnClickListener<CarModelTag>() {
        @Override
        public void onItemClick(CarModelTag carModelTag) {
            carManagementViewModel.getDelCarModelRelativeMerits().setValue(null);
            carManagementViewModel.delCarModelRelativeMerits(carModelTag.getId()).observe(CarCompareFragment.this, new Observer<BaseResponse<String>>() {
                @Override
                public void onChanged(BaseResponse<String> stringBaseResponse) {
                    if(stringBaseResponse==null){
                        return;
                    }
                    carManagementViewModel.getDelCarModelRelativeMerits().removeObserver(this);
                    if (stringBaseResponse.isSuccess()) {
                        carModelTagAdapter1.removeCurrentClickItem();
                    } else {
                        showToast(stringBaseResponse.getMsg());
                    }
                }
            });
        }
    };
    OnClickListener<CarModelTag> carModelTagOnClickListener2 = new OnClickListener<CarModelTag>() {
        @Override
        public void onItemClick(CarModelTag carModelTag) {
            carManagementViewModel.getDelCarModelRelativeMerits().setValue(null);
            carManagementViewModel.delCarModelRelativeMerits(carModelTag.getId()).observe(CarCompareFragment.this, new Observer<BaseResponse<String>>() {
                @Override
                public void onChanged(BaseResponse<String> stringBaseResponse) {
                    if(stringBaseResponse==null){
                        return;
                    }
                    carManagementViewModel.getDelCarModelRelativeMerits().removeObserver(this);
                    if (stringBaseResponse.isSuccess()) {
                        carModelTagAdapter2.removeCurrentClickItem();
                    } else {
                        showToast(stringBaseResponse.getMsg());
                    }
                }
            });
        }
    };
    OnClickListener<CarModelTag> carModelTagOnClickListener3 = new OnClickListener<CarModelTag>() {
        @Override
        public void onItemClick(CarModelTag carModelTag) {
            carManagementViewModel.getDelCarModelRelativeMerits().setValue(null);
            carManagementViewModel.delCarModelRelativeMerits(carModelTag.getId()).observe(CarCompareFragment.this, new Observer<BaseResponse<String>>() {
                @Override
                public void onChanged(BaseResponse<String> stringBaseResponse) {
                    carManagementViewModel.getDelCarModelRelativeMerits().removeObserver(this);
                    if (stringBaseResponse.isSuccess()) {
                        carModelTagAdapter3.removeCurrentClickItem();
                    } else {
                        showToast(stringBaseResponse.getMsg());
                    }
                }
            });
        }
    };
    OnClickListener<CarModelTag> carModelTagOnClickListener4 = new OnClickListener<CarModelTag>() {
        @Override
        public void onItemClick(CarModelTag carModelTag) {

            carManagementViewModel.getDelCarModelRelativeMerits().setValue(null);
            carManagementViewModel.delCarModelRelativeMerits(carModelTag.getId()).observe(CarCompareFragment.this, new Observer<BaseResponse<String>>() {
                @Override
                public void onChanged(BaseResponse<String> stringBaseResponse) {
                    if(stringBaseResponse==null){
                        return;
                    }
                    carManagementViewModel.getDelCarModelRelativeMerits().removeObserver(this);
                    if (stringBaseResponse.isSuccess()) {
                        carModelTagAdapter4.removeCurrentClickItem();
                    } else {
                        showToast(stringBaseResponse.getMsg());
                    }
                }
            });
        }
    };
    CarModelTagAdapter.OnAddItemListener onAddItemListener = new CarModelTagAdapter.OnAddItemListener() {
        @Override
        public void onAdd(CarModelTag carModelTag) {
            mCarModelTag = carModelTag;
            etTag.requestFocus();
            Input input=new Input(etTag, 0, true);
            input.setNeedGone(llInput);
            mainViewModel.getInput().setValue(input);
            llInput.setVisibility(View.VISIBLE);
        }
    };

    View.OnLayoutChangeListener onLayoutChangeListener = new View.OnLayoutChangeListener() {
        @Override
        public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
            Rect rect = new Rect();
            getActivity().getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
            if (bottom != 0 && oldBottom != 0 && bottom - rect.bottom <= 0) {
                // Toaster.showLong("隐藏");
                RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                        RelativeLayout.LayoutParams.MATCH_PARENT, Tool.dip2px(getActivity(), 0));
                params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
                llInput.setLayoutParams(params);

            } else {
                RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                        RelativeLayout.LayoutParams.MATCH_PARENT, Tool.dip2px(getActivity(), 50));
                params.setMargins(Tool.dip2px(getActivity(), 15), rect.bottom - Tool.dip2px(getActivity(), 180), Tool.dip2px(getActivity(), 15), 0);
                llInput.setLayoutParams(params);
            }
        }
    };

    @OnClick(R.id.iv_add)
    public void add() {
        carManagementViewModel.getAddCarModelRelativeMerits().setValue(null);
        carManagementViewModel.addCarModelRelativeMerits(mCarModelTag.getCarModelId(), mCarModelTag.getTagType(), etTag.getText().toString())
                .observe(this,observer );
    }
    public void getCarModelRelativeMerits(CarModel carModel){

        carManagementViewModel.getCarModelRelativeMerits(carModel.getId())
                .observe(CarCompareFragment.this, new Observer<BaseResponse<CarModelRelativeMerits>>() {
                    @Override
                    public void onChanged(BaseResponse<CarModelRelativeMerits> carModelRelativeMeritsBaseResponse) {
                        if (carModelRelativeMeritsBaseResponse==null) {
                            return;
                        }
                        carManagementViewModel.getCarModelRelativeMerits().removeObserver(this);
                        List<CarModelTag> list = new ArrayList<>();
                        CarModelTag carModelTag = new CarModelTag();
                        carModelTag.setTagContext("添加标签");
                        carModelTag.setCarModelId(carModel.getId());
                        list.addAll(carModelRelativeMeritsBaseResponse.getData().getGoodPointTagList());
                        list.add(carModelTag);
                        carModelTagAdapter2 = new CarModelTagAdapter(getContext(),
                                list, 2, 2);
                        rv2.setAdapter(carModelTagAdapter2);
                        List<CarModelTag> list1 = new ArrayList<>();
                        list1.addAll(carModelRelativeMeritsBaseResponse.getData().getBadPointTagList());
                        list1.add(carModelTag);
                        carModelTagAdapter4 = new CarModelTagAdapter(getContext(),
                                list1, 3, 4);
                        carModelTagAdapter2.setOnClickListener(carModelTagOnClickListener2);
                        carModelTagAdapter4.setOnClickListener(carModelTagOnClickListener4);
                        carModelTagAdapter2.setOnAddItemListener(onAddItemListener);
                        carModelTagAdapter4.setOnAddItemListener(onAddItemListener);
                        rv4.setAdapter(carModelTagAdapter4);
                        carManagementViewModel.getCarModelRelativeMerits().removeObserver(this);
                    }
                });

    }
    @Override
    public void onDestroyView() {
        getActivity().getWindow().getDecorView().removeOnLayoutChangeListener(onLayoutChangeListener);
        super.onDestroyView();
    }

    Observer observer=new Observer<BaseResponse<CarModelTag>>() {
        @Override
        public void onChanged(BaseResponse<CarModelTag> carModelTagBaseResponse) {
            if (carModelTagBaseResponse!=null&&carModelTagBaseResponse.isSuccess()) {
                llInput.setVisibility(View.GONE);
                mainViewModel.getInput().setValue(new Input(llInput, 0, false));
                switch (mCarModelTag.getType()) {
                    case 1:
                        carModelTagAdapter1.addItem(carModelTagBaseResponse.getData());
                        break;
                    case 2:
                        carModelTagAdapter2.addItem(carModelTagBaseResponse.getData());
                        break;
                    case 3:
                        carModelTagAdapter3.addItem(carModelTagBaseResponse.getData());
                        break;
                    case 4:
                        carModelTagAdapter4.addItem(carModelTagBaseResponse.getData());
                }
            } else if(carModelTagBaseResponse!=null){
                showToast(carModelTagBaseResponse.getMsg());
            }
        }
    };
}
